<?php

namespace app\modules\admin\controllers;

use yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use app\modules\admin\components\BaseAdminController;
use app\modules\admin\models\LoginForm;
use app\modules\admin\models\User;
use app\components\Wechat;
use app\models\Tenant;
use app\components\Loyalty;


/**
 * Default controller for the `admin` module
 */
class DefaultController extends BaseAdminController
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'test'],
                'rules' => [
                    [
                        'actions' => ['logout', 'test'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        // $a = $this->session('appid');
        // echo $a;
        $tenantName = Yii::$app->session->get('tenantName');
        if (empty($tenantName)){
            Yii::$app->user->logout();
            return $this->redirect(['login']);
        }
        return $this->render('index', [
            'tenant' => $tenantName
        ]);
    }

    public function actionSetPay()
    {
        $re = Wechat::set_pay(['card_id' => 'p2Rmrt56_YLiCcUp3QDOs4lIQyo8', 'is_open' => true]);
        echo "<pre/>";
        var_dump($re);die;
    }

    // 登录
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect(['default/set-tenant']);
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    // 登出
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->redirect(['login']);
    }

    // 注册新用户
    public function actionRegister()
    {
        $model = new User();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            
            $model->generatePassword($model->password);
            $model->generateAuthKey();
            $model->generateAccessToken();
            $model->insert();

            $this->redirect(['default/login']);
        }

        return $this->render('register', [
            'model' => $model,
        ]);
    }

    public function actionAbc()
    {
        $uname = [
            'A' => '10',
            'B' => '20',
            'C' => '20',
            'D' => '10',
            'E' => '10',
            'F' => '30',
            'H' => '10',
            'G' => '30',
        ];
        // $uname = [
        //     'A-D-E' => '10',
        //     'B-C' => '20',
        // ];
        $new_uname = [];
        foreach($uname as $k => $v) {
            $new_uname[] = ['name' => $k, 'score' => $v];
        }
        $count = count($new_uname);

        echo '<pre>';
        for ($i = 0; $i < $count; $i++) {
            echo '$i:' . $i . '->';
            if (isset($new_uname[$i])) {
                echo $i . '->';
                $a = $new_uname[$i];
                print_r($a);echo '->';
                foreach ($new_uname as $k => $v) {
                    if ($a['name'] != $v['name']) {
                        if ($a['score'] == $v['score']) {
                            print_r($v);
                            $a['name'] .= '-' . $v['name'];
                            unset($new_uname[$k]);
                        }
                    }
                }
                $new_uname[$i] = $a;
            }
        }
        krsort($new_uname);
        $this->bp($new_uname);

        foreach($new_uname as $k => $v) {
            for($i = $k; $i < ($count-1-$k); $i++) {
                if (isset($new_uname[$i])) {
                    echo $i . '-';
                    if ($v['score'] == $new_uname[$i+1]['score']) {
                        $new_uname[$k]['name'] .= '-' . $new_uname[$i+1]['name'];
                        unset($new_uname[$i+1]);
                    }
                }
                
                // var_dump($new_uname);die;
            }
            var_dump($new_uname);die;
        }
    }
    public function actionError($message)
    {
        $this->layout = 1;
//        $exception = Yii::$app->errorHandler->exception;
//        if ($exception !== null) {
//            return $this->render('myerror');
//        }
        return $this->render('myerror',['message' => $message]);

    }

    //删除loyalty数据
    public function actionDelectLoyalty()
    {
        $session = Yii::$app->session;
        $tenant = Tenant::find()->where(['appid' => "wxfe151ff0add3fb49"])->one();
        if (empty($tenant->identifier)) {
//            throw new ServerErrorHttpException('identifier not found');
        }

        // 设置loyalty config
        if (empty($tenant->tenant_id) || empty($tenant->loyalty_accountid) || empty($tenant->loyalty_username) || empty($tenant->loyalty_password)) {
//            throw new ServerErrorHttpException('loyalty config not found');
        } else {
            $loyaltyConfig = [
                'tenant_id' => $tenant->tenant_id,
                'app_id' => $tenant->appid,
                'loyalty_accountid' => $tenant->loyalty_accountid,
                'loyalty_username' => $tenant->loyalty_username,
                'loyalty_password' => $tenant->loyalty_password,
                'loyalty_url' => $tenant->loyalty_url,
            ];
            $session->set('loyaltyConfig', $loyaltyConfig);
        }
//        $re = Loyalty::campaign_list();
//        $re = Loyalty::customer_delete(['code' => 'MOMO34']);
        $re = Loyalty::customer_search(['mobile' => '17713607873']);
//        $re = Loyalty::customer_search(['code' => '80200152']);
//        $re = Loyalty::customer_update(['code' => '007' , 'wechat_openid' => ""]);
        echo "<pre/>";
        var_dump($re);die;
    }
    //创建测试用户
    public function actionCreateUser()
    {
//       $re =  Loyalty::customer_create(["code" => '008','mobile' => '15196359975']);
//       $re =  Loyalty::customer_update(["code" => '008','wechat_openid' => '']);
       $re =  Loyalty::customer_search(['mobile' => '13438257234']);
//        $re  = Loyalty::customer_get(['wechat_openid' => "o2Rmrt5U54B4kkWj5YfQ67g3V3xM"]);
        echo "<pre/>";
        var_dump($re);die;
    }

    //设置当前tenant
    public function actionSetTenant()
    {
        $this->layout = 'tenant';
        $models = Tenant::find()->all();
        if (empty($models)){
            return $this->redirect(['tenant/create']);
        }
        $tenants = [];
        $appids = [];
        foreach ($models as $k => $v) {
            $tenants[] = $v['name'];
            $appids[] = $v['appid'];
        }
        // 修改现有session中的appid
        if (Yii::$app->request->isPost) {
            $id = Yii::$app->request->post('id');
            $appid = $appids[$id];
            $tenant = Tenant::find()->where(['appid' => $appid])->one();
            $this->session('identifier', $tenant['identifier']);
            $this->session('tenantName', $tenant['name']);
            $this->session('appid', $appid);
            return $this->redirect(['index']);
        }
        
        // 查询session是否有appid，没有则返回空，有则显示
        $appid = Yii::$app->session->get('appid');
        // $appid = 'wx577957a019a2f435';
        $key = array_search($appid, $appids);
        if (isset($key)) {
            $appid = $tenants[$key];
        } else {
            $appid = null;
        }
        return $this->render('settenant', [
            'tenants' => $tenants,
            'appid' => $appid,
            'key' => $key,
        ]);
    }

    public function actionSession()
    {
        $session = Yii::$app->session;
        $a = $session->remove('tenantName');
        var_dump($a);
    }
}
